package org.skydiveapplibrary.ui;

import org.skydiveapplibrary.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

public class NumberPreference extends DialogPreference
{
	private TextView numberField;
	Integer initialValue;

	public NumberPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		setDialogLayoutResource(R.layout.number_preference);
	}

	// Update the text with saved values
	@Override
    protected void onBindDialogView(View view)
	{
        super.onBindDialogView(view);
        
//        int mNumber = getPersistedInt(0);
        
		// init fields
 		numberField = (TextView) view.findViewById(R.id.NumberField);
// 		numberField.setText(FormatUtility.toNumericString(mNumber));
 		
 		if ( this.initialValue != null ) numberField.setText(FormatUtility.toNumericString(initialValue));
	}
	
	@Override
    protected void onDialogClosed(boolean positiveResult)
	{
        super.onDialogClosed(positiveResult);
        
        if (positiveResult)
        {
        	String numberString = numberField.getText() == null ? null : numberField.getText().toString();
    		initialValue = FormatUtility.toInteger(numberString, 0);
    		
    		// save new value
            if (callChangeListener(initialValue)) {
            	persistInt(initialValue);
            }
    		
        }
    }
	
	@Override
	protected void onSetInitialValue(boolean restorePersistedValue,
			Object defaultValue) {
		int def = ( defaultValue instanceof Number ) ? (Integer)defaultValue
				: ( defaultValue != null ) ? Integer.parseInt(defaultValue.toString()) : 1;
		if ( restorePersistedValue ) {
			this.initialValue = getPersistedInt(def);
		}
		else this.initialValue = (Integer)defaultValue;
		
		persistInt(initialValue);
	}
		
	@Override
	protected Object onGetDefaultValue(TypedArray a, int index) {
		return a.getInt(index, 0);
	}
}
